/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/4/6
 **/
'use strict';
var webpack = require('webpack');
var co =require('co');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var fse =require('fs-extra');
var fs  =require('fs');

var basicConfigFactory =require('./webpack.config.factory')();
// let BundleBarGeneratePlugin =require('./webpack-plugin/bundle-bar-generate-plugin');
let path  =require('path');

//把组件条的数量等信息统计出来;;

let widgetMap = require('./compile-widget-bar-task');

let entry = {};
for(let widgetNameSpace in widgetMap){
    let item =  widgetMap[widgetNameSpace];
    let widgetCompileName  = item.widgetName+Math.random();
    let widgetPCompileName  = item.widgetName+"-p"+Math.random();

    entry[widgetCompileName] = path.join('..',item.widgetPath);
    entry[widgetPCompileName] = path.join('..',item.widgetPath+"-p");
    widgetMap[widgetNameSpace].jsFilePath ='bundle-'+widgetCompileName+'.js';
    widgetMap[widgetNameSpace].cssFilePath =widgetCompileName+'-styles.css';
    console.log(widgetMap[widgetNameSpace].cssFilePath,'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    widgetMap[widgetNameSpace].jsProxyFilePath ='bundle-'+widgetPCompileName+'.js';
}


let isProd  =false;

let plugins = [];
if(isProd){
    plugins = [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
}

let proLoader =path.join(__dirname,'./loader/widget-pre-loader.js');
//
// if(process.cwd().includes('settings')){
//     proLoader = './loader/widget-pre-loader.js';
// }


var devConfig =basicConfigFactory.buildConfig({
    entry,
    output: {
        path: './dist/barBuild',
        filename: 'bundle-[name].js',
        chunkFilename:'chunk.[id].[name].[hash].js',
    },
    module: {
        preLoaders:[
            // { test: /\.js$/, exclude: /node_modules/, loader: '@qianmi/xsite-widget-bar-loader',query: {widgetMap: widgetMap,topDir:path.join(__dirname,'../..')}},
            { test: /\.js$/, exclude: /node_modules/, loader: proLoader,query: {widgetMap: widgetMap,topDir:path.join(__dirname,'../..')}},
        ]
    },
    plugins: [
        new ExtractTextPlugin("[name]-styles.css"),
    ].concat(plugins)
});


var compiler = webpack(devConfig);
compiler.run(function(err, stats) {
    if(err){
        console.error(err);
    }else{
        if(stats.compilation.errors.length>0){
            throw stats.compilation.errors[0];
        }
    
    
        co((function * (){
            for(let ns  in widgetMap){
                let widgetInfo  =  widgetMap[ns];
                console.log('准备写入bar文件==============>:',widgetInfo,'\n');
                yield mvFile(widgetInfo);
            }
            fse.outputJson(path.join(__dirname,'../dist','barIndex.json'),widgetMap,(err)=>{
            });
        })());
        
    }
});


/**
 *
 * @param widgetInfo
   {
   jsFilePath:"",
   cssFilePath:"",
   widgetName:"",
   widgetNameSpace:"",
   }
 */
function * mvFile(widgetInfo){
            
            
            
        console.log('mvFile',widgetInfo);
        let jsFilePath  = path.join(__dirname,'../dist/barBuild',widgetInfo.jsFilePath);
        let cssFilePath   = path.join(__dirname,'../dist/barBuild',widgetInfo.cssFilePath);
        let jsProxyFilePath  = path.join(__dirname,'../dist/barBuild',widgetInfo.jsProxyFilePath);
        let widgetPath  =  path.join(__dirname,'../dist/barRepo',widgetInfo.widgetNameSpace);
        
        
        fse.move(jsProxyFilePath, widgetPath+"-p.js",  {clobber:true},function (err) {
            if (err){
                console.error(err)
                console.dir(widgetInfo);
                return;
            }
        });
    
        fse.move(jsFilePath, widgetPath+".js",  {clobber:true},function (err) {
            if (err){
                console.error(err)
                console.dir(widgetInfo);
                return;
            }
        });
    
        fse.move(cssFilePath, widgetPath+".css", {clobber:true},function (err) {
            if (err){
                //console.error(err)
                //console.dir(widgetInfo);
                return;
            }
        });
    
    
        let results = yield [isFileReadAble(jsProxyFilePath),isFileReadAble(jsFilePath),isFileReadAble(cssFilePath)];
        widgetInfo.jsProxyFilePath = results[0]  ? widgetInfo.widgetNameSpace+"-p.js" :"";
        widgetInfo.jsFilePath = results[1]?widgetInfo.widgetNameSpace+".js":"";
        widgetInfo.cssFilePath = results[2]?widgetInfo.widgetNameSpace+".css":"";
}


/**
 * 文件 是否可读 , 如果文件不存在 , 也当做不可读
 * @param filePath
 * @return {Promise}
 */
function isFileReadAble(filePath){
    return new Promise((resolve,reject)=>{
        fs.access(filePath, fs.constants.R_OK, (err) => {
            if(err){
                resolve(false);
            }else  {
                resolve(true);
            }
            console.log(err ? 'no access!' : 'can read/write');
        });
    })
}